﻿module SelectorsTest

open NUnit.Framework
open UriParsing
open HtmlScanner
open HtmlParser
open Dom
open HtmlDom
open DummyHost
open DocumentFactory
open CssTypes
open Matcher


let parse html =
    let doc = createDocument (fun doc->()) blankUri (DummyLoader()) (DummyHost())
    parseHtmlTokens doc (scan html) 
    doc

let matchesInDoc (docNode:Document) selector =
    let rec allElements (elem:Element) =
        seq { yield elem
              for elem in elem.childElements do yield! allElements elem }

    let matches selector =
        [for elem in allElements docNode.documentElement do if matchSelector selector elem then yield elem]

    [for elem in matches selector -> elem.attributeOrDefault("id", "?")]


//test code
let docNode = parse """
<html>
<body>
    
<p id=1>hello</p>

<ul id=2>
<li id=3>hello</li>
</ul>

<li id=4>hello</li>

</body>
</html>
"""

[<Test>]
let simpleMatch() =
    let selector = SimpleSelector(NodeSelector(TypeSelector("li"),[]))
    let ids = matchesInDoc docNode selector
    Assert.AreEqual(["3";"4"], ids)

[<Test>]
let descendentMatch() =
    let selector = ContextualSelector(
                        NodeSelector(TypeSelector("li"),[]),
                        DescendentSelector(
                            SimpleSelector(NodeSelector(TypeSelector("ul"),[]))))
    let ids = matchesInDoc docNode selector
    Assert.AreEqual(["3"], ids)